package com.study.bind;

import com.study.pojo.Configuration;
import com.study.sqlSession.SqlSessionImpl;

import java.util.HashMap;
import java.util.Map;

public class MapperRegistry {
    private final Configuration config;
    private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<>();

    public MapperRegistry(Configuration config) {
        this.config = config;
    }

    public <T> void addMapper(Class<T> type) {
        knownMappers.put(type, new MapperProxyFactory(type));
    }

    public <T> T getMapper(Class<T> type, SqlSessionImpl sqlSession) throws Exception {
        final MapperProxyFactory<?> mapperProxyFactory = knownMappers.get(type);
        if (mapperProxyFactory == null) {
            throw new Exception("Type " + type + " is not known to the MapperRegistry.");
        }
        return (T) mapperProxyFactory.newInstance(sqlSession);
    }
}
